package com.sushengren.easyword.converters;

import com.sushengren.easyword.constants.DefaultConverters;
import com.sushengren.easyword.model.WriteData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 自动转换器
 *
 * @author sushengren
 */
public class AutoConverter implements Converter {

    @Override
    public WriteData convertToWriteData(String key, Object obj) {
        if (checkString(obj)) {
            return DefaultConverters.getConverter(StringConverter.class.getName()).convertToWriteData(key, obj);
        }
        if (checkList(obj)) {
            return DefaultConverters.getConverter(ListConverter.class.getName()).convertToWriteData(key, obj);
        }
        return DefaultConverters.getConverter(StringConverter.class.getName()).convertToWriteData(key, obj);
    }

    /**
     * 确认为字符串
     *
     * @param obj obj
     * @return boolean
     */
    private boolean checkString(Object obj) {
        if (obj == null) {
            return false;
        }
        Class<?> clazz = obj.getClass();
        if (clazz.isEnum()) {
            return true;
        }
        if (clazz.isPrimitive()) {
            return true;
        }
        List<String> basicTypeList = new ArrayList<>(9);
        Collections.addAll(basicTypeList,
                "java.lang.String",
                "java.lang.Boolean",
                "java.lang.Character",
                "java.lang.Byte",
                "java.lang.Short",
                "java.lang.Integer",
                "java.lang.Long",
                "java.lang.Float",
                "java.lang.Double"
        );
        return basicTypeList.contains(clazz.getName());
    }

    /**
     * 确认为列表
     *
     * @param obj obj
     * @return boolean
     */
    private boolean checkList(Object obj) {
        return obj instanceof Iterable;
    }

}
